package com.manager.user.module.service;

import com.manager.commons.Constant;
import com.manager.commons.mybatis.dao.GenericDao;
import com.manager.commons.mybatis.service.GenericService;
import com.manager.user.module.dao.GenFilesDao;
import com.manager.user.module.dao.UserOrganizationDao;
import com.manager.user.module.entity.GenFiles;
import com.manager.user.module.entity.PlatformParameter;
import com.manager.user.module.entity.view.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * GenUserService
 * 用户表
 *
 * @author manager
 * @version 1.0
 */
@Service
public class FileDownloadService extends GenericService<GenFiles> {

    @Autowired
    private GenFilesDao filesDao;

    @Autowired
    private UserOrganizationDao userOrganizationDao;

    @Override
    public GenericDao<GenFiles> getDao() {
        return filesDao;
    }

    public PlatformParameter getBaseParameter(String code) {
        return userOrganizationDao.getBaseParameter(code);
    }

    public List<GenFiles> getPathIds(Map<String, Object> params) {
        String ids = getParamsString(params, "ids");
        String[] idArray = ids.split(",");
        List<String> intList = Arrays.asList(idArray);
        Map<String, Object> map = new HashMap<String, Object>() {{
            put("_ids", intList);
        }};
        return filesDao.queryIdsPath(map);
    }

    public List<TreeNode> getTreeNode(List<String> intList, String rootParentId) {
        List<String> leveIds = filesDao.queryLevelId(new HashMap<String, Object>() {{
            put("_ids", intList);
        }});

        List<TreeNode> allNodes = filesDao.findAllNodes(new HashMap<String, Object>() {{
            put("_ids", leveIds);
        }});
        // 构建节点ID到节点的映射
        Map<String, TreeNode> nodeMap = new HashMap<>();
        for (TreeNode node : allNodes) {
            nodeMap.put(node.getId(), node);
        }
        List<TreeNode> rootNodes = new ArrayList<>();
        for (TreeNode node : allNodes) {
            String parentId = node.getParentId();
            // 如果是根节点（父ID等于指定的根父ID），加入根节点列表
            if (rootParentId.equals(parentId)) {
                rootNodes.add(node);
            } else {
                // 非根节点：从map中找到父节点，将当前节点添加到父节点的子节点集合
                TreeNode parentNode = nodeMap.get(parentId);
                if (parentNode != null) {
                    parentNode.addChild(node);
                } else {
                    // 父节点不存在时的容错处理（可根据业务需求调整）
                    // 例如：将其视为根节点或忽略
                    rootNodes.add(node);
                }
            }
        }
        // 返回包含默认根节点的列表
        return rootNodes;
    }


    public GenFiles findPid(String id) {
        return filesDao.findPid(id);
    }
}
